﻿using Microsoft.Build.Construction;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text.Json;
using System.Threading;

namespace xycn.framework.PublishSolution
{
    enum CompileType { Debug, Release }

    class Program
    {
        /// <summary>
        /// 解决方案文件名
        /// </summary>
        public static string slnFileName = "";

        /// <summary>
        /// 生成目录
        /// </summary>
        public static string outPath = "";

        /// <summary>
        /// 调用本生成程序的正在编译的项目
        /// </summary>
        public static string callProject = "";

        /// <summary>
        /// 编译模式，包括Debug、Release
        /// </summary>
        public static CompileType compileType;

        /// <summary>
        /// 程序启动路径
        /// </summary>
        public static string RuntimeDir = "";

        /// <summary>
        /// 记录生成时间
        /// </summary>
        public static StreamWriter logFileWriter = null;

        static void Main(string[] args)
        {
            //获取当前运行路径
            string path = Assembly.GetExecutingAssembly().Location;
            RuntimeDir = Path.GetDirectoryName(path);

            ProjectBuilder.LoadProjectBuildInfos();

            logFileWriter = new StreamWriter(RuntimeDir + "\\build.log", false, System.Text.Encoding.UTF8);

            //记录输入参数
            string input_args = "";
            for (int i = 0; i < args.Length; i++)
            {
                string arg = args[i];
                input_args = input_args + "arg[" + i.ToString() + "]:" + arg + ";\t";
            }
            logFileWriter.WriteLine("输入参数：" + input_args);
            if (args.Length < 4)
            {
                Console.WriteLine("需要输入解决方案路径及文件名（可以使用相对路径）和生成路径，格式如下：");
                logFileWriter.WriteLine("需要输入解决方案路径及文件名（可以使用相对路径）和生成路径，格式如下：");
                Console.WriteLine("BuildEnvironment [主程序名称] [解决方案文件名] [解决方案生成路径] [debug|release]");
                logFileWriter.WriteLine("BuildEnvironment [主程序名称] [解决方案文件名] [解决方案生成路径] [debug|release]");
                return;
            }
            else
            {
                callProject = args[0];
                slnFileName = args[1];
                outPath = args[2];
                string compile_type = args[3].ToLower();
                if (compile_type == "release")
                {
                    compileType = CompileType.Release;
                }
                else
                {
                    compileType = CompileType.Debug;
                }
            }

            SolutionTree.BuildSolutionTree(outPath, slnFileName);

            //递归遍历解决方案树，调用对应项目处理对象ProjectAnalyzer进行处理
            AnalyzeProjectNode(SolutionTree.rootNode.childeNodes);

            logFileWriter.Flush();
            logFileWriter.Close();

            ProjectBuilder.SaveProjectBuildInfos();
            return;
        }

        /// <summary>
        /// 递归分析解决方案树中的项目节点，并调用dotnet命令，将模块及其依赖包输出到指定目录
        /// </summary>
        private static void AnalyzeProjectNode(List<ProjectNode> nodes)
        {
            if (nodes.Count == 0)
                return;

            foreach (ProjectNode node in nodes)
            {
                //创建目录
                if (node.projType == SolutionProjectType.SolutionFolder)
                {
                    //if (!Directory.Exists(node.targetBuildDir))
                    System.IO.Directory.CreateDirectory(node.targetBuildDir);
                }
                else
                {
                    if (node.projInfo.ProjectName == Program.callProject)
                        continue;

                    ProjectBuilder project_analyzer = new ProjectBuilder(node);
                    project_analyzer.Build();
                }

                AnalyzeProjectNode(node.childeNodes);
            }
        }
    }
}
